package com.xiaoyu.awakening.ai.search.service.impl;

import com.xiaoyu.awakening.ai.search.context.AwkSearchContext;
import com.xiaoyu.awakening.ai.search.model.AwkSearchContent;
import com.xiaoyu.awakening.ai.search.model.dto.SearchResultDTO;
import com.xiaoyu.awakening.ai.search.service.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

/**
 * 检索服务
 *
 * @author wangxiaoyu
 * @date 2025/8/5 14:56
 * @since v1.0
 */
@Service
@Slf4j
public class AwkSearchServiceImpl implements IAwkSearchService {
    @Resource
    private IAwkIntentionService intentionService;
    @Resource
    private IAwkCallbackService callbackService;
    @Resource
    private IAwkReRankService reRankService;
    @Resource
    private IAwkHighLightService highLightService;
    @Resource
    private IAwkSearchPlanService searchPlanService;
    @Resource
    private IAwkFusionService fusionService;

    @Override
    public SearchResultDTO<AwkSearchContent> search(AwkSearchContext<AwkSearchContent> context) {
        StopWatch watch = new StopWatch("awk-search" + context.getSearchId());
        // 1. 意图识别
        watch.start("intention-detect");
        context.setIntentionDetectList(intentionService.detect(context.getSourceSearchRequest()));
        watch.stop();

        // 2. 搜索计划:根据意图选择搜索计划，根据意图召回策略生成精排计划
        watch.start("search-plan");
        context.setCallbackRoutes(callbackService.allRouts());
        context.setRankDefinitions(reRankService.getRerankersDefinition());
        searchPlanService.doSearchPlan(context);
        watch.stop();

        // 2. 数据并行召回
        watch.start("callback-route");
        callbackService.callback(context);
        watch.stop();

        // 3. 排序
        watch.start("re-rank");
        reRankService.rank(context);
        watch.stop();

        // 4. 融合
        watch.start("fusion");
        fusionService.fusion(context);
        watch.stop();

        // 5. 高亮
        watch.start("high-light");
        if (context.getSourceSearchRequest().getReturnHighLightEnable()) {
            highLightService.highLight(context);
        }
        watch.stop();

        log.info("search cost:{}", watch.prettyPrint());

        // 6. 发布搜索记录
        publishRecordEvent(context);
        return context.getHitResult();
    }

    private void publishRecordEvent(AwkSearchContext<AwkSearchContent> context) {
    }
}
